package com.ymx.darling.wrapper;

import com.ymx.darling.bean.entity.BeanInfo;
import com.ymx.darling.bean.entity.BeanInfoManager;
import com.ymx.darling.util.LambdaUtil;
import com.ymx.darling.wrapper.fragment.FromSegment;
import com.ymx.darling.wrapper.fragment.SqlSegment;
import com.ymx.darling.wrapper.fragment.TableInfo;
import com.ymx.darling.wrapper.fragment.UpdateSetSegment;
import com.ymx.darling.wrapper.fragment.lambda.LambdaGetter;

import java.util.Map;

/**
 * update delete语句构造器
 * @author 爱Java的小于
 */
public class UpdateWrapper extends Wrapper<UpdateWrapper> {
    private String tableName;
    private final FromSegment from = new FromSegment();
    private final UpdateSetSegment upsetSplit = new UpdateSetSegment();

    /**
     * 拼接表名
     * @param tableName 表名
     * @return wrapper
     */
    public UpdateWrapper from(String tableName) {
        this.tableName = tableName;
        this.from.from(tableName);
        return this;
    }

    public UpdateWrapper from(TableInfo tableInfo) {
        return this.from(tableInfo.getTableName());
    }

    public UpdateWrapper from(Class<?> fromType) {
        BeanInfo beanInfo = BeanInfoManager.getBeanInfo(fromType);
        return this.from(beanInfo.getTableName());
    }

    /**
     * 拼接普通的字段值 字段值会当做占位符放入站位发入列表中
     * @param colum 字段名称
     * @param value 字段值
     * @return wrapper
     */
    public UpdateWrapper set(String colum, Object value){
        this.upsetSplit.set(colum, value);
        return this;
    }

    public <L> UpdateWrapper set(LambdaGetter<L> column, Object value) {
        return this.set(LambdaUtil.getColumnName(column), value);
    }

    /**
     * 拼接普通的字段值 字段值会当做占位符放入站位发入列表中
     * @param colum 字段名称
     * @param value 字段值
     * @return wrapper
     */
    public UpdateWrapper set(boolean condition, String colum, Object value){
        if (condition) {
            this.upsetSplit.set(colum, value);
        }
        return this;
    }

    public <L> UpdateWrapper set(boolean condition, LambdaGetter<L> column, Object value) {
        return this.set(condition, LambdaUtil.getColumnName(column), value);
    }

    /**
     * 拼接表达式 比如 colum1 = column1 + 100 字段表达式为直接拼接 不会放入占位符列表中
     * @param expressionTemplate 字段表达式模版
     * @param param 字段表达式参数
     * @return wrapper
     */
    public UpdateWrapper setSegment(String expressionTemplate, Object... param){
        this.upsetSplit.setSegment(expressionTemplate, param);

        return this;
    }


    public String getTableName() {
        return this.tableName;
    }

    @Override
    protected Map<String, SqlSegment> getSqlSegmentMap() {
        Map<String, SqlSegment> sqlSegmentMap = super.getSqlSegmentMap();
        sqlSegmentMap.put("set", this.upsetSplit);
        sqlSegmentMap.put("from", this.from);

        return sqlSegmentMap;
    }
}
